<template>
  <el-card class="logs-page">
    <!-- 工具栏：操作人 + 时间范围 + 删除 -->
    <div class="toolbar">
      <el-input
        v-model="filters.operator"
        placeholder="操作人"
        clearable
        @clear="fetchList"
        @keyup.enter="fetchList"
        size="small"
        class="toolbar-item"
      />
      <el-input
        v-model="filters.action"
        placeholder="操作行为"
        clearable
        @clear="fetchList"
        @keyup.enter="fetchList"
        size="small"
        class="toolbar-item"
      />
      <el-date-picker
        v-model="filters.range"
        type="daterange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        @change="onRangeChange"
        size="small"
        class="toolbar-item"
      />
      <el-button type="primary" size="small" @click="fetchList">
        查询
      </el-button>
      <el-button
        type="danger"
        size="small"
        :disabled="!multiple.length"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <!-- 日志表格 -->
    <el-table
      v-loading="loading"
      :data="logs"
      stripe
      @selection-change="multiple = $event"
      style="width: 100%"
    >
      <el-table-column type="selection" width="50" />

      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="userId" label="操作人ID" width="120" />
      <el-table-column prop="action" label="操作行为" min-width="180" />
      <el-table-column prop="targetTable" label="目标表" width="120" />
      <el-table-column prop="targetId" label="目标ID" width="100" />
      <el-table-column prop="description" label="描述" min-width="200" />
      <el-table-column prop="createdAt" label="时间" width="180" />
      <el-table-column label="操作" width="140" align="center" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            circle
            :icon="Document"
            @click="openDetail(row.id)"
          >
          </el-button>
          <el-button
            type="danger"
            circle
            :icon="Delete"
            @click="handleDelete(row.id)"
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper, sizes, total"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="日志详情"
      v-model="detailVisible"
      width="600px"
      :before-close="() => (detailVisible = false)"
    >
      <el-descriptions
        v-if="currentLog"
        :title="`日志 #${currentLog.id}`"
        column="1"
        border
      >
        <el-descriptions-item label="用户ID">
          {{ currentLog.userId }}
        </el-descriptions-item>
        <el-descriptions-item label="行为">
          {{ currentLog.action }}
        </el-descriptions-item>
        <el-descriptions-item label="目标表">
          {{ currentLog.targetTable }}
        </el-descriptions-item>
        <el-descriptions-item label="目标ID">
          {{ currentLog.targetId }}
        </el-descriptions-item>
        <el-descriptions-item label="描述">
          <pre>{{ currentLog.description }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="时间">
          {{ currentLog.createdAt }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { pageLogs, getLog, deleteLogs } from "@/api/logs";
import { Delete, Document } from "@element-plus/icons-vue";
// 列表状态
const filters = reactive({
  operator: "",
  action: "",
  startDate: null,
  endDate: null,
  range: [],
});
const loading = ref(false);
const logs = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const multiple = ref([]);

// 详情对话框
const detailVisible = ref(false);
const currentLog = ref(null);

function onRangeChange(val) {
  if (Array.isArray(val) && val.length === 2) {
    filters.startDate = val[0];
    filters.endDate = val[1];
  } else {
    filters.startDate = null;
    filters.endDate = null;
  }
}

// 拉取分页
async function fetchList() {
  loading.value = true;
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...(filters.action ? { action: filters.action } : {}),
      ...(filters.operator ? { userId: filters.operator } : {}),
      ...(filters.startDate ? { startDate: filters.startDate } : {}),
      ...(filters.endDate ? { endDate: filters.endDate } : {}),
    };
    const res = await pageLogs(params);
    const data = res.data;
    logs.value = data.items || [];
    total.value = data.total || 0;
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
}

// 分页回调
function onPageChange(p) {
  pageNum.value = p;
  fetchList();
}
function onSizeChange(s) {
  pageSize.value = s;
  pageNum.value = 1;
  fetchList();
}

// 查看详情
async function openDetail(id) {
  try {
    const res = await getLog(id);
    currentLog.value = res.data;
    detailVisible.value = true;
  } catch (err) {
    console.error(err);
  }
}

// 单条删除
function handleDelete(id) {
  ElMessageBox.confirm("确认删除该日志？", "提示", { type: "warning" }).then(
    async () => {
      await deleteLogs([id].join(","));
      ElMessage.success("删除成功");
      fetchList();
    }
  );
}

// 批量删除
function handleBatchDelete() {
  const ids = multiple.value.map((i) => i.id);
  if (!ids.length) return;
  ElMessageBox.confirm(`确认删除这 ${ids.length} 条日志？`, "提示", {
    type: "warning",
  }).then(async () => {
    await deleteLogs(ids.join(","));
    ElMessage.success("批量删除成功");
    multiple.value = [];
    fetchList();
  });
}

onMounted(fetchList);
</script>

<style scoped>
.logs-page {
  padding: 16px;
}
.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-bottom: 16px;
}
.toolbar-item {
  width: 180px;
}
.pagination {
  text-align: right;
  margin-top: 12px;
}
</style>
